package com.example.interCeptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 定义一个时间拦截器的bean
 */
@Component
public class TimeInterCeptor implements HandlerInterceptor {

    private LocalDateTime begin;

    Logger log = LoggerFactory.getLogger(TimeInterCeptor.class);

    //请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        begin = LocalDateTime.now();
        log.info("当前请求："+request.getRequestURI()+",开始时间："+begin);
        return true;
    }

    //请求之前渲染之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LocalDateTime end = LocalDateTime.now();
        long seconds = Duration.between(begin, end).toMillis();//计算请求之前和渲染中间的差值
        log.info("请求之前渲染之后花费时间："+seconds);
    }
}
